<script setup lang="ts">
import { Plus ,Edit, Delete} from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { getBrandListAPI, deleteBrandAPI, addBrandAPI,updateBrandAPI , getBrandByIdAPI} from '@/api/product/brand'
import type { BrandItem, UploadImageResponse } from '@/types/product/brand'
import { ElMessage, ElMessageBox} from 'element-plus'

// 品牌列表数据
const tableData  = ref<BrandItem[]>()

// 分页数据
const curentPage = ref({
    page: 1,
    pageSize: 5,
    total: 40
})

// 数据加载
const loading = ref(false)

// 获取品牌列表数据
const getBrandList = async () => {
    loading.value = true
    const res = await getBrandListAPI(curentPage.value.page,curentPage.value.pageSize)
   console.log(res);
    tableData.value = res.data.records
    curentPage.value.total = res.data.total
    // console.log(tableData.value);
   tableData.value.forEach((item: BrandItem) => {
        if(!item.logoUrl.includes('http://')) {
            item.logoUrl = 'http://' + item.logoUrl
        }
    })
    loading.value = false
}

// 初始化
onMounted(() => {
    getBrandList()
})

// 切换页码
const handleCurrentChange = (page: number) => {
    // console.log(page);
    curentPage.value.page = page
    getBrandList()
}

// 切换页数
const handleSizeChange = (pageSize: number) => {
    curentPage.value.pageSize = pageSize
    getBrandList()
}

// 编辑品牌
const editBrand = async (row: BrandItem) => {
    // console.log(row);
    isAdd.value = false
    // 发送请求获取品牌详情
    const res = await getBrandByIdAPI(row.id as number)
    res.data.logoUrl.includes('http://') ? '' : res.data.logoUrl = 'http://' + res.data.logoUrl
    formData.value.name = res.data.tmName
    formData.value.logo = res.data.logoUrl
    formData.value.id = res.data.id
    console.log(formData.value);
    
    uploadImgList.value = [{url:res.data.logoUrl}]
    previewUrl.value = res.data.logoUrl
    dialogVisible.value = true

    
}

// 删除品牌
const deleteBrand = (row: BrandItem) => {
    // 开启弹框提示用户
    ElMessageBox.confirm('确认删除该品牌码？', "温馨提示",{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        // 确认逻辑
        const res = await deleteBrandAPI(row.id as number)
        if(res.code === 200) {
            ElMessage.success('删除成功')
            getBrandList()
        }
        
    }).catch(async () => {
        // 取消逻辑
    })
}

// 添加品牌
const addBrand = () => {
    isAdd.value = true
    dialogVisible.value = true
}

// 弹出框显示
const dialogVisible = ref(false)

// 删除logo
const handleRemove = () => {
    
}

// 预览图片
const previewUrl = ref('')

// 预览图片
const handlePictureCardPreview = () => {
    previewDialogVisible.value = true
}

// 弹框表单数据
const formData = ref({
    name: '',
    // 上传图片列表
    logo: '',
    id:  0
})

// 弹框表单对象
const formRef = ref<any>()

// 校验规则
const rules =  {
    name: [
        {
            required: true,
            message: '请输入品牌名称',
            trigger: 'blur'
        }
    ],
    logo: [
        {
            required: true,
            message: '请上传品牌logo',
            trigger: 'blur'
        }
    ]
}

// 图片自定义校验

// 图片预览框
const previewDialogVisible = ref(false)

// 上传图片超出限制
const handleExceed = () => {
    ElMessage.warning('最多上传1张图片')
}

// 上传图片列表
const uploadImgList = ref<any>([])

// 上传图片成功
const handleSuccess = (res: UploadImageResponse) => {
    // console.log(res);
    previewUrl.value = res.data
    formData.value.logo = res.data
    formRef.value.clearValidate('logo')
    
}

// 表单确认按钮
const submitForm = () => {
    console.log(formData.value);
    
    // 整体校验
    formRef.value.validate( async (valid: boolean) => {
        if(valid) {
            // 判断是否是添加状态
            if (isAdd.value) {
                    // 校验通过
                const params = {
                    logoUrl: previewUrl.value,
                    tmName: formData.value.name,
                }

                // 发送请求
                const res = await  addBrandAPI(params)
                if(res.code === 200) {
                    ElMessage.success('添加品牌成功')
                    // 关闭弹框
                    closeDialog()
                    // 重新获取列表
                    getBrandList()
                }
            } else {
                const params = {
                    logoUrl: previewUrl.value,
                    tmName: formData.value.name,
                    id: formData.value.id
                }
                const res = await updateBrandAPI(params)
                console.log(res);
                if(res.code === 200) {
                    ElMessage.success('修改品牌成功')
                    // 关闭弹框
                    closeDialog()
                    // 重新获取列表
                    getBrandList()
                }
                

            }
            
            
        }
    })
}

// 关闭弹框
const closeDialog = () => {
    // 重置表单
    formData.value.name = ''
    // 重置图片
    formData.value.logo = ''
    uploadImgList.value = []
    formRef.value.clearValidate()
    previewUrl.value = ''
    dialogVisible.value = false
    
}

// 添加或更新状态控制
const isAdd = ref(true)

// 上传图片前校验文件参数
const onBeforeUpload  = (file: any) => {
    if(file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        if(file.size / 1024 / 1024 < 4) {
            return true
        } else {
            ElMessage.warning('上传图片大小不能超过 4MB!')
            return false
        }
    } else {
        ElMessage.warning('上传图片只能是 JPG、PNG、GIF 格式!')
        return false
    }
}

</script>
<template>
    <div>
        <el-card >
            <el-button :icon="Plus" type="primary" size="large" @click="addBrand">添加品牌</el-button>
            <el-table v-loading="loading" style="margin-top: 20px; width: 100%;" :data="tableData" border >
                <el-table-column header-align="center" align="center" type="index" label="序号" width="80" />
                <el-table-column  header-align="center" align="center" prop="tmName" label="品牌名称" width="180" />
                <el-table-column header-align="center" align="center" prop="logoUrl" label="品牌LOGO">
                    <template v-slot="{ row }">
                        <img :src="row.logoUrl" alt="" class="logo">
                    </template>
                </el-table-column>
                <el-table-column  header-align="center" align="center"  label="操作" >
                    <template v-slot="{ row }">
                        <el-button @click="editBrand(row)" type="primary" size="large" circle :icon="Edit"></el-button>
                        <el-button @click="deleteBrand(row) " type="danger" size="large" :icon="Delete" circle ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                style="margin-top: 20px;"
                v-model:page-size="curentPage.pageSize"
                :page-sizes="[5, 10, 15, 20]"
                v-model:current-page="curentPage.page"
                :background="true"
                layout="prev,pager,next,jumper,->, sizes ,total"
                :total="curentPage.total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                />
        </el-card>
        <el-dialog @close="closeDialog" v-model="dialogVisible" :title="isAdd ? '添加品牌' : '编辑品牌'" style="max-width: 500px;">
            <el-form ref="formRef" :rules="rules " :model="formData" label-width="100px" style="padding: 10px 20px; width: 100%;"  >
                <el-form-item label="品牌名称" style="width: 58%;" prop="name">
                    <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logo">
                    <el-upload
                        drag
                        v-model:file-list="uploadImgList"
                        action="/admin/product/fileUpload"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :on-success="handleSuccess"
                        :before-upload="onBeforeUpload"
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog style="max-width: 500px;" title="图片预览" v-model="previewDialogVisible">
                        
                        <img class="preview" w-full :src="previewUrl"  alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-row style="width: 100%;" justify="end">
                        <el-button type="default" @click="closeDialog">取消</el-button>
                        <el-button type="primary" @click="submitForm">确认</el-button>
                </el-row>
            </template>
        </el-dialog>
    </div>
    
</template>



<style scoped>
.logo {
    width: 100px;
}
.preview {
    width: 100%;
}
::v-deep(.el-upload-dragger ) {
    border: 0;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>@/api/product/brand